from fastapi import FastAPI
from contextlib import asynccontextmanager
from redis.asyncio import Redis
from backend.config.config import settings
from backend.common.logging import logger

redis_client: Redis | None = None

def get_redis() -> Redis:
    if redis_client is None:
        raise RuntimeError("Redis not initialized")
    return redis_client


@asynccontextmanager
async def redis_lifespan(app: FastAPI):
    global redis_client
    redis_client = Redis(
        host=f"{settings.REDIS_HOST}", 
        port=f"{settings.REDIS_PORT}",
        password=f"{settings.REDIS_PASSWORD}", 
        db=f"{settings.REDIS_DB}", 
        decode_responses=True
        )
    try:
        # 连接测试
        await redis_client.ping()
        logger.info(f"🛢️  Redis connected to DB {settings.REDIS_DB}")
    except Exception as e:
        logger.error(f"❌ Redis connection failed: {e}")
        raise RuntimeError("Redis connection failed") from e
    try:
        yield
    finally:
        await redis_client.aclose()
        logger.info("🧹 Redis closed")
